import * as titleService from '@/services/title';
import { message } from 'antd';
import { DEFAULT_RESPONE_SUCCESS } from '@/constants';

export default {
  namespace: 'title',

  state: {
    current: 1,
    total: 0,
    data: [],
    rowKey: 'id'
  },

  subscriptions: {

  },

  effects: {
    *queryData({ payload }, { call, put }) {
      const { callback, current = 1, pageSize, ...extra } = payload;

      const response = yield call(titleService.queryData, { pageNo: current, pageSize }, { ...extra });
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        const { result = {} } = response;
        const { content: data = [], totalElements: total = 0 } = result;

        if (typeof callback === 'function') {
          callback(data)
        } else {
          yield put({
            type: 'changeState',
            payload: {
              data,
              current,
              pageSize,
              total
            }
          });
        }
      }
    },
    *saveOrUpdateData({ payload }, { call, put }) {
      const { id, data, ...extra } = payload;
      const option = {
        method: 'POST',
        body: Array.isArray(data) ? data : [data]
      };
      let response = {};
      if (!id) {
        response = yield call(titleService.saveData, option);
      } else {
        response = yield call(titleService.updateData, option);
      }
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        message.success(!id ? '新增头衔成功' : '编辑头衔成功', 1);
        yield put({
          type: 'changeState',
          payload: { visible: false, editData: {} }
        });
        yield put({ type: 'queryData', payload: { ...extra } });
      }
    },
    *deleteData({ payload }, { call, put }) {
      const { data, ...extra } = payload;
      const option = {
        method: 'POST',
        body: Array.isArray(data) ? data : [data]
      };
      const response = yield call(titleService.deleteData, option);
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        message.success('删除头衔成功', 1);
        yield put({ type: 'queryData', payload: { ...extra } });
      }
    }
  },

  reducers: {
    clear(state, { payload }) {
      return {
        current: 1,
        total: 0,
        data: [],
        rowKey: 'id'
      };
    },
    changeState(state, { payload }) {
      return {
        ...state,
        ...payload
      };
    }
  },
};
